//
//  SelectPhoneAreaCodeVC.m
//  MASK
//
//  Created by Jane on 16/11/8.
//  Copyright © 2016年 ushareit. All rights reserved.
//

#import "SelectPhoneAreaCodeVC.h"

#import "RegionalModel.h"
#import "CountryCodeConversion.h"


#define kAreaCodeDocument @"countryChinese"

#define RGB0X(rgbValue) [UIColor colorWithRed: ((float)((rgbValue & 0xFF0000) >> 16)) / 255.0 \
green: ((float)((rgbValue & 0xFF00) >> 8)) / 255.0 \
blue: ((float)(rgbValue & 0xFF)) / 255.0 alpha: 1.0]

@interface SelectPhoneAreaCodeVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>{
    NSMutableDictionary *_data;
    BOOL    isSearching;
}

@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *keys;
@property (strong, nonatomic) NSMutableDictionary *cityDic;
@property (weak, nonatomic) IBOutlet UIView *BarView;
@property (weak, nonatomic) IBOutlet UILabel *titleNameLB;

@end

@implementation SelectPhoneAreaCodeVC

-(void)viewDidLoad{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = @[(__bridge id)RGB0X(0xe62f17).CGColor, (__bridge id)RGB0X(0xcc1616).CGColor];
    gradientLayer.locations = @[@0.0f, @0.7f];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1.0, 0);
    gradientLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, CGRectGetHeight(self.BarView.frame));
    [self.BarView.layer insertSublayer:gradientLayer atIndex:0  ];
    
    _titleNameLB.text = NSLocalizedString(@"select_city", nil);
    self.searchBar.placeholder =NSLocalizedString(@"select_city_search", nil);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _searchBar.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    [self readData];
}

-(void)readData{
    NSMutableArray *countryNameArr = [NSMutableArray array];
    NSLocale *locale = [NSLocale currentLocale];
    NSArray *countryArray = [NSLocale ISOCountryCodes];
    for (NSString *countryCode in countryArray)
    {
        NSString *displayNameString = [locale displayNameForKey:NSLocaleCountryCode value:countryCode];
        if (displayNameString == nil)
            displayNameString = @"";
        
        RegionalModel *model = [[RegionalModel alloc] init];
        model.countryCode = countryCode;
        model.countryName = displayNameString;
        model.countryNumber = [CountryCodeConversion accordingToTheChosenAreaCode:countryCode];
        if (model.countryNumber.length > 0) {
            [countryNameArr addObject:model];
        }
    }
    [self createIndexes:countryNameArr];
}


-(void)createIndexes:(NSMutableArray *)modelArray{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    SEL selector = @selector(countryName);
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    NSInteger index, sectionTitlesCount = [[collation sectionTitles] count];
    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    //设置sections数组初始化：元素包含userObjs数据的空数据
    for (index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [newSectionsArray addObject:array];
    }
    
    for (RegionalModel *model in modelArray) {
        NSInteger sectionNumber = [collation sectionForObject:model collationStringSelector:selector];
        NSMutableArray *sectionUserObjs = [newSectionsArray objectAtIndex:sectionNumber];
        //添加内容到section中
        [sectionUserObjs addObject:model];
    }
    for (index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *userObjsArrayForSection = [newSectionsArray objectAtIndex:index];
        NSArray *sortedUserObjsArrayForSection = [collation sortedArrayFromArray:userObjsArrayForSection collationStringSelector:selector];
        [newSectionsArray replaceObjectAtIndex:index withObject:sortedUserObjsArrayForSection];
    }
    _keys = [NSMutableArray array];
    NSArray * allSections = [collation sectionIndexTitles];
    for (NSUInteger index  = 0 ; index < [allSections count]; index++) {
        if ([newSectionsArray[index] count]>0) {
            [dic setObject:newSectionsArray[index] forKey:allSections[index]];
            [_keys addObject:allSections[index]];
        }
    }
    _data  = [dic mutableCopy];
    [_tableView reloadData];

}

#pragma mark Table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_keys count];
}
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section{
    
    if ([_keys count] == 0){
        return 0;
    }
    NSString *key = [_keys objectAtIndex:section];
    NSArray *nameSection = [_data objectForKey:key];
    return [nameSection count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    NSString *key = [_keys objectAtIndex:section];
    NSArray *nameSection = [_data objectForKey:key];
    RegionalModel *model = nameSection[indexPath.row];
    static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             SectionsTableIdentifier ];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
                                      reuseIdentifier: SectionsTableIdentifier ];
    }
    cell.textLabel.text = model.countryName;
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    if (model.countryNumber.length > 0) {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"+%@",model.countryNumber];
    }else{
        cell.detailTextLabel.text = @"";
    }
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;//section头部高度
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = RGB0X(0xefeff4);
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 20)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = RGB0X(0x7e7e7e);
    label.font = [UIFont boldSystemFontOfSize:11];
    label.text = _keys[section];
    [view addSubview:label];
    
    return view;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    NSString *key = [_keys objectAtIndex:section];
    NSArray *nameSection = [_data objectForKey:key];
    RegionalModel *model = nameSection[indexPath.row];
    if (self.block != nil) {
        self.block(model.countryNumber,model.countryName,model.countryCode);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchBar resignFirstResponder];
    _searchBar.text = @"";
    isSearching = NO;
    [tableView reloadData];
    return indexPath;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if ([_keys count] == 0)
        return nil;
    NSString *key = [_keys objectAtIndex:section];
    if (key == UITableViewIndexSearch)
        return nil;
    return key;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (isSearching)
        return nil;
    return _keys;
}

#pragma mark Search Bar Delegate Methods
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSString *searchTerm = [searchBar text];
    [self handleSearchForTerm:searchTerm];
}


- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    isSearching = YES;
    [_tableView reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar
    textDidChange:(NSString *)searchTerm
{
    if ([searchTerm length] == 0)
    {
        [self resetSearch];
        [_tableView reloadData];
        return;
    }
    [self handleSearchForTerm:searchTerm];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    isSearching = NO;
    _searchBar.text = @"";
    [self resetSearch];
    [_tableView reloadData];
    [searchBar resignFirstResponder];
}

-(void)resetSearch{
    [_data removeAllObjects];
//    NSString *plistPath = [[NSBundle mainBundle] pathForResource:kAreaCodeDocument ofType:@"plist"];
//    _data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
//    NSArray *sortedArray = [_data allKeys];
//    NSArray *keyArr = [sortedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
//        return [obj1 compare:obj2 options:NSNumericSearch];
//    }];
//    _keys = [keyArr mutableCopy];
    [self readData];
}
- (void)handleSearchForTerm:(NSString *)searchTerm{
    NSMutableArray *sectionsToRemove = [NSMutableArray array];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [self resetSearch];
    for (NSString *key in self.keys) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:[_data valueForKey:key]] ;
        NSMutableArray *toRemove = [NSMutableArray array];
        for (RegionalModel *model in array) {
            if ([model.countryName rangeOfString:searchTerm
                            options:NSCaseInsensitiveSearch].location == NSNotFound)
                [toRemove addObject:model];
        }
        if ([array count] == [toRemove count])
            [sectionsToRemove addObject:key];
        [array removeObjectsInArray:toRemove];
        if (array.count > 0) {
            [dic setObject:array forKey:key];
        }
        NSLog(@"array= %ld  == %@",(unsigned long)array.count,dic);
    }
    [_data removeAllObjects];
    _data = dic;
    [self.keys removeAllObjects];
    self.keys = [[dic allKeys] mutableCopy];
    [_tableView reloadData];
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [_searchBar resignFirstResponder];
}

- (IBAction)didClickBack:(id)sender {

    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
